//
//  NewCreatOneChapter.m
//  shusheng
//
//  Created by rimi on 16/7/14.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "NewCreatOneChapter.h"
#import "NewEditorWord.h"


/**< 打印路径 */
#define NSLOG_DOCUMENTS_PATH2_CHAPTER  NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject);

/**< 沙盒地址 */
#define DOCUMENT_PATH_CHAPTER NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject
/**< 文件管理类 */
#define DEFAULT_FILEMANAGER_CHAPTER [NSFileManager defaultManager]

//static NSString *const ChapterPlist    = @"/UserAllChpatersPlistList.plist";
//[DOCUMENT_PATH stringByAppendingString:[NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]]



@implementation NewCreatOneChapter

- (int)creatchapterOfOneNovelid:(NSString *)novelId
                      chapterId:(NSString *)chapterId
                    chapterName:(NSString *)chapterName{
   
    
    if (chapterId.length == 0 || chapterName.length == 0) {//未命名
        NSLog(@"章节未有ID或未命名");
        return 1;
        
    }else if ([self isExistingNovelId:novelId chapterId:chapterId]){//防止一本小说中相同章节Id存在
        NSLog(@"ID重复");//yes~>名字相同，
        return 2;
        
    }else{
        //存储操作
        int result = [self saveNovelid:novelId chapterId:chapterId chapterName:chapterName];
        //服务器同步
        [self networkSynchronization];

        return result;
    }

}

//查询操作
+ (NSArray *)readOfNovelId:(NSString *)novelId{
    //路径
    NSString * path = [DOCUMENT_PATH_CHAPTER stringByAppendingString:[NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    
     NSMutableArray *chapterArray = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
//        [MBProgressHUD showSuccess:@"没有数据"];
    }else{
        NSLog(@"查询操作====%@",datas);
        
        for (int i = 0; i < datas.count; i ++) {
            if ([novelId isEqualToString:datas[i][@"novelId"]]&&[[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [chapterArray addObject:datas[i]];
            };
        }
        NSLog(@"得到%@",chapterArray);
    }
    
    return  chapterArray;
}
//查询操作
- (NSArray *)readOfNovelId:(NSString *)novelId{
    
    NSString * path = [DOCUMENT_PATH_CHAPTER stringByAppendingString: [NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    
    NSMutableArray *chapterArray = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
//        [MBProgressHUD showSuccess:@"没有数据"];
    }else{
        NSLog(@"查询操作====%@",datas);
        
        for (int i = 0; i < datas.count; i ++) {
            if ([_novelId isEqualToString:datas[i][@"novelId"]]&&[[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [chapterArray addObject:datas[i]];
            }
        }
        NSLog(@"得到%@",chapterArray);
        
        if (chapterArray.count == 0) {
            NSLog(@"该小说还没有章节。");
//            [MBProgressHUD showSuccess:@"没有数据"];
        }
    }
    
    return  chapterArray;
}

//遍历已有小说id
- (BOOL)isExistingNovelId:(NSString *)novelId
                  chapterId:(NSString *)chapterId{
    //调用查询
    //得到名字
    //对比
    
    NSArray *novelChapters = [self readOfNovelId:novelId];//查看操作
    
    for (int i = 0; i < novelChapters.count ; i++) {
        NSDictionary *dic = [NSDictionary dictionary];
        dic = novelChapters[i];
        NSString *c = [dic objectForKey:@"chapterId"];
        if ([chapterId isEqualToString:c]) {
            NSLog(@"重名");
            return YES;
        }
    }
    NSLog(@"没重名");
    return NO;
}

//存储操作
- (int)saveNovelid:(NSString *)novelId
         chapterId:(NSString *)chapterId
       chapterName:(NSString *)chapterName{
    
    //获取沙盒（plist）路径,拼接
    NSString * path = [DOCUMENT_PATH_CHAPTER stringByAppendingString: [NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]];
    
    //判断plist文件路径是否存在~如果存在，则根据plist文件路径初始化根数组（代表有数据，取出原有数据再存，才不会覆盖==获取原有的数据）；否则直接初始化根数组。
    NSMutableArray * rootArr = nil;
    if ([DEFAULT_FILEMANAGER_CHAPTER fileExistsAtPath:path ]) {
        rootArr=[NSMutableArray  arrayWithContentsOfFile:path];
    }else{
        rootArr =[@[]mutableCopy];
    }
    
    //打包用户信息
    NSString *txtName = [NSString stringWithFormat:@"novelId=%@->chapterId=%@->novelName%@->chapterName=%@.txt",_novelId,_chapterId,_novelName,_chapterName];
    NSLog(@"%@",txtName);
    NSDictionary * infoDict = @{@"userId":[AVUser currentUser].objectId,@"novelId":novelId,@"chapterId":chapterId,@"chapterName":chapterName,@"time":[ToolOfBasic nowTime],@"word":txtName};
    
    [NewEditorWord creatOneTxtFile:txtName];
//    NSLog(@"章节位置txt创建文本内容：%@",[NewEditorWord readFileName:txtName]);
    
    
    //将用户信息存到根数组
    [rootArr insertObject:infoDict atIndex:0];
     NSLog(@"%@",infoDict);
    //(将根数组写入沙盒文件中)
    if ([rootArr writeToFile:path atomically:YES]) {
        NSLog(@"plist存储成功");
        NSLOG_DOCUMENTS_PATH2_CHAPTER;
        
        //txt
//        [NewEditorWord creatOneTxtFile:txtName];
        return 3;
        
    }else{
        NSLog(@"plist存储失败");
        return 5;
    }
    
   
    
}

- (void)networkSynchronization{
    
}

//删除小说所有章节操作
+ (NSArray *)deleteAllChaptersOfNovelId:(NSString *)novelId
                                 userId:(NSString *)userId{
    
    NSString * path = [DOCUMENT_PATH_CHAPTER stringByAppendingString: [NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"查询章节plist====%@",datas);
    NSMutableArray *chapterArray = [@[] mutableCopy];
    NSMutableArray *otherChaptersArray = [@[] mutableCopy];
 
    
    if (!datas || datas.count == 0) {
        NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
        
    }else{
        
        for (int i = 0; i < datas.count; i ++) {
            if ([novelId isEqualToString:datas[i][@"novelId"]] && [[AVUser currentUser].objectId isEqualToString:userId]) {
                [chapterArray addObject:datas[i]];
            }else{
                [otherChaptersArray addObject:datas[i]];
                
            }
            
            NSLog(@"得到chapterArray%@------otherChaptersArray:%@",chapterArray,otherChaptersArray);
        }
    }
 

    //存
    [otherChaptersArray writeToFile:path atomically:YES];
    return chapterArray;
}

//遍历所有章节，删除对应小说id的对应章节id元素
+ (NSArray *)deleteAChapterOfNovelId:(NSString *)novelId
                           chapterId:(NSString *)chapterId
                              userId:(NSString *)userId{
    NSString * path = [DOCUMENT_PATH_CHAPTER stringByAppendingString: [NSString stringWithFormat:@"%@UserAllChpatersPlistList.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"查询章节plist====%@",datas);

    NSMutableArray *chapterArray = [@[] mutableCopy];
    NSMutableArray *otherChaptersArray = [@[] mutableCopy];
    NSMutableArray *allArr = [@[] mutableCopy];
    
    
   
    if (!datas || datas.count == 0) {
        NSLog(@"然而还没有数据。/(ㄒoㄒ)/~~");
        
    }else{
        
        for (int i = 0; i < datas.count; i ++) {
            if ([novelId isEqualToString:datas[i][@"novelId"]] && [[AVUser currentUser].objectId isEqualToString:userId]) {
                [chapterArray addObject:datas[i]];
            }else{
                [otherChaptersArray addObject:datas[i]];
                
            }
            
            NSLog(@"得到chapterArray%@------otherChaptersArray:%@",chapterArray,otherChaptersArray);
        }
    }
    
    
    //删除
    //得到元素
    //删元素
    if (chapterArray && chapterArray.count > 0) {
        
        for (int j = 0; j < chapterArray.count; j ++) {
            
            if ([chapterArray[j][@"chapterId"]isEqualToString:chapterId]) {
                 NSLog(@"chapterId%@将要删除的章节--%@",chapterId,chapterArray[j]);
                [chapterArray removeObjectAtIndex:j];
            }
        }
       
    }
    
     //拼接
    for (int i = 0; i < chapterArray.count; i ++) {
        [allArr addObject:chapterArray[i]];
    }
    for (int j = 0; j < otherChaptersArray.count; j ++) {
        [allArr addObject:otherChaptersArray[j]];
    }
    
    //存
    [allArr writeToFile:path atomically:YES];
    //返回该小说id的未删除章节
    return chapterArray;
    
}

@end
